#include <iostream>
#include "Log.hpp"
#include "comm.hpp"
using namespace std;

#define TRY_AGAIN 5
void Usage(const string &proc)
{
    std::cout << "Usage:" << proc << "tcp_ip tcp_port" << std::endl;
}

bool connectserver(const string &serverip, const uint16_t &serverport, int &cnt)
{

    // 1.创建套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        cerr << "create sock error" << endl;
        return false;
    }

    // 2.bind,不用显示绑定ip和port，连接的时候os再自动分配

    std::string mode;
    bool ret = true;
    ssize_t n = 0;
    ssize_t m = 0;
    string inbuffer;
    char server_list[1024];
    // 3.进行连接
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());

    socklen_t len = sizeof(server);
    n = connect(sockfd, CONV(&server), len);
    if (n < 0)
    {
        cerr << "connect error" << endl;
        ret = false;
        goto end;
    }
    cnt = 0;

    m = read(sockfd, server_list, sizeof(server_list) - 1);
    if (m > 0)
    {
        server_list[m] = 0;
        std::cout << "服务器提供的服务列表是：" << server_list << std::endl;
    }

    // 客户端输入要执行的任务模式
    std::cout << "Please Select Service# ";
    getline(std::cin, inbuffer);
    write(sockfd, inbuffer.c_str(), inbuffer.size());

    // 4.发送消息
    cout << "Enter> ";
    getline(cin, inbuffer);
    if (inbuffer == "quit")
        return true;
    n = write(sockfd, inbuffer.c_str(), inbuffer.size());
    if (n > 0)
    {
        char buffer[1024];
        m = read(sockfd, buffer, sizeof(buffer) - 1);
        if (m > 0)
        {
            buffer[m] = 0;
            cout << "get a echo message: " << buffer << endl;
        }
        else if (m == 0)
        {
            return true;
        }
        else
        {
            ret = false;
            goto end;
        }
    }
    else
    {
        ret = false;
        goto end;
    }
end:
    close(sockfd);
    return ret;
}
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(Usage_Err);
    }
    string serverip = argv[1];
    uint16_t serverport = stoi(argv[2]);

    // 每隔1秒进行重新连接服务器
    int cnt = 1;
    while (cnt <= TRY_AGAIN)
    {
        bool ret = connectserver(serverip, serverport, cnt);
        if (ret)
        {
            break;
        }
        else
        {
            cout << "Try connecting to the server again..., cnt: " << cnt << endl;
            cnt++;
        }
        sleep(1);
    }

    return 0;
}